from flask import Flask, request, jsonify, send_from_directory, Response
from flask_cors import CORS
import asyncio
import os
import aiohttp
from config import Config
from backend.bilibili_service import BilibiliService, run_async
from backend.ai_service import AIService
from backend.enhanced_api import register_enhanced_routes
from backend.bilibili_login import login_service

app = Flask(__name__, static_folder='frontend', static_url_path='')
CORS(app)

# 初始化服务
bilibili_service = BilibiliService()
ai_service = AIService()

# 注册增强API路由
register_enhanced_routes(app)


@app.route('/')
def index():
    """返回首页"""
    return send_from_directory('frontend', 'index.html')


@app.route('/api/analyze', methods=['POST'])
def analyze_video():
    """分析视频的主接口"""
    try:
        data = request.get_json()
        url = data.get('url', '')
        
        if not url:
            return jsonify({
                'success': False,
                'error': '请提供B站视频链接'
            }), 400
        
        # 提取BVID
        bvid = BilibiliService.extract_bvid(url)
        if not bvid:
            return jsonify({
                'success': False,
                'error': '无效的B站视频链接'
            }), 400
        
        # 获取视频信息
        video_info_result = run_async(bilibili_service.get_video_info(bvid))
        if not video_info_result['success']:
            return jsonify(video_info_result), 400
        
        video_info = video_info_result['data']
        
        # 获取字幕
        print("[信息] 开始获取字幕...")
        subtitle_result = run_async(bilibili_service.get_video_subtitles(bvid))
        
        # 获取弹幕（用于分析）
        print("[信息] 开始获取弹幕...")
        danmaku_result = run_async(bilibili_service.get_video_danmaku(bvid, limit=200))
        danmaku_texts = []
        if danmaku_result['success']:
            danmaku_texts = danmaku_result['data']['danmakus']
            print(f"[信息] 获取到 {len(danmaku_texts)} 条弹幕")
        
        # 获取评论（用于分析）
        print("[信息] 开始获取评论...")
        comments_result = run_async(bilibili_service.get_video_comments(bvid, max_pages=10))
        comments_data = []
        if comments_result['success']:
            comments_data = comments_result['data']['comments']
            print(f"[信息] 获取到 {len(comments_data)} 条评论")
        
        # 获取统计数据
        print("[信息] 开始获取统计数据...")
        stats_result = run_async(bilibili_service.get_video_stats(bvid))
        stats_data = stats_result['data'] if stats_result['success'] else {}
        
        # 构建内容
        content = ''
        has_subtitle = False
        
        if subtitle_result['success'] and subtitle_result['data'].get('has_subtitle'):
            content = subtitle_result['data']['full_text']
            has_subtitle = True
            print(f"[信息] 使用字幕作为主要内容（{len(content)}字）")
        else:
            # 使用弹幕和简介
            if danmaku_texts:
                content = '\n'.join(danmaku_texts)  # 使用所有获取到的弹幕（已限制在200条内）
                content = f"【视频简介】\n{video_info.get('desc', '')}\n\n【弹幕内容】\n{content}"
                print(f"[信息] 使用弹幕作为内容（{len(danmaku_texts)}条）")
            else:
                content = f"【视频简介】\n{video_info.get('desc', '')}"
        
        if not content or len(content) < 50:
            return jsonify({
                'success': False,
                'error': '无法获取视频内容（无字幕且无有效弹幕）'
            }), 400
        
        # 获取视频帧进行多模态分析（智能优化：根据视频时长自动调整参数）
        print("[信息] 开始提取视频关键帧...")
        frames_result = run_async(bilibili_service.extract_video_frames(bvid))

        video_frames = None
        if frames_result['success']:
            video_frames = frames_result['data']['frames']
            print(f"[信息] 成功提取 {len(video_frames)} 帧画面")
        else:
            print(f"[警告] 视频帧提取失败: {frames_result['error']}")
            print("[信息] 📝 将仅使用文本内容进行分析")
        
        # 调用AI生成分析（包含视频帧）
        analysis_result = ai_service.generate_full_analysis(video_info, content, video_frames)
        
        if not analysis_result['success']:
            return jsonify(analysis_result), 500
        
        # 返回完整结果（包含四大板块所需的所有数据）
        return jsonify({
            'success': True,
            'data': {
                'video_info': video_info,
                'stats': stats_data,
                'has_subtitle': has_subtitle,
                'has_video_frames': bool(video_frames),
                'frame_count': len(video_frames) if video_frames else 0,
                'content_length': len(content),
                'danmaku_count': len(danmaku_texts),
                'comment_count': len(comments_data),
                'danmaku_preview': danmaku_texts[:20] if danmaku_texts else [],  # 前20条弹幕
                'comments_preview': comments_data[:10] if comments_data else [],  # 前10条评论
                'analysis': analysis_result['data']['full_analysis'],
                'parsed': analysis_result['data']['parsed'],
                'tokens_used': analysis_result['data']['tokens_used']
            }
        })
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'服务器错误: {str(e)}'
        }), 500


@app.route('/api/video/info', methods=['POST'])
def get_video_info():
    """获取视频信息"""
    try:
        data = request.get_json()
        url = data.get('url', '')
        
        bvid = BilibiliService.extract_bvid(url)
        if not bvid:
            return jsonify({
                'success': False,
                'error': '无效的B站视频链接'
            }), 400
        
        result = run_async(bilibili_service.get_video_info(bvid))
        return jsonify(result)
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'获取视频信息失败: {str(e)}'
        }), 500


@app.route('/api/video/subtitle', methods=['POST'])
def get_video_subtitle():
    """获取视频字幕"""
    try:
        data = request.get_json()
        url = data.get('url', '')
        
        bvid = BilibiliService.extract_bvid(url)
        if not bvid:
            return jsonify({
                'success': False,
                'error': '无效的B站视频链接'
            }), 400
        
        result = run_async(bilibili_service.get_video_subtitles(bvid))
        return jsonify(result)
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'获取字幕失败: {str(e)}'
        }), 500



@app.route('/api/image-proxy')
def image_proxy():
    """B站图片代理，解决防盗链问题"""
    image_url = request.args.get('url')
    if not image_url:
        return jsonify({'error': '缺少图片URL'}), 400

    # 修复：解码URL参数
    import urllib.parse
    image_url = urllib.parse.unquote(image_url)

    # 修复：如果URL缺少协议，添加https://
    if image_url.startswith('//'):
        image_url = 'https:' + image_url
    elif not image_url.startswith(('http://', 'https://')):
        # 如果不是完整URL，添加https://
        image_url = 'https://' + image_url

    # 只允许代理B站的图片
    if not any(domain in image_url for domain in ['hdslb.com', 'bilibili.com']):
        return jsonify({'error': '不支持的图片域名'}), 400

    try:
        # 添加正确的headers来访问B站图片
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Referer': 'https://www.bilibili.com',
            'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Accept-Encoding': 'identity',  # 避免压缩问题
            'Connection': 'close'
        }

        # 使用同步请求获取图片
        import requests
        print(f"[调试] 代理图片: {image_url}")
        response = requests.get(image_url, headers=headers, timeout=10)

        if response.status_code != 200:
            print(f"[错误] 图片请求失败: HTTP {response.status_code}")
            return jsonify({'error': f'获取图片失败: {response.status_code}'}), 404

        # 获取图片类型
        content_type = response.headers.get('content-type', 'image/jpeg')

        # 返回图片内容
        return Response(response.content, mimetype=content_type)

    except Exception as e:
        print(f"[错误] 图片代理失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': f'获取图片失败: {str(e)}'}), 500


@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({
        'success': True,
        'status': 'running',
        'message': 'BiliBili智能学习平台 Ultra版运行中'
    })


@app.route('/api/bilibili/login/start', methods=['POST'])
def start_bilibili_login():
    """开始B站扫码登录"""
    try:
        result = run_async(login_service.start_login())
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'启动登录失败: {str(e)}'
        }), 500


@app.route('/api/bilibili/login/status', methods=['POST'])
def check_login_status():
    """检查登录状态"""
    try:
        data = request.get_json()
        session_id = data.get('session_id', '')

        if not session_id:
            return jsonify({
                'success': False,
                'error': '缺少session_id'
            }), 400

        result = run_async(login_service.check_login_status(session_id))
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'检查登录状态失败: {str(e)}'
        }), 500


@app.route('/api/bilibili/login/logout', methods=['POST'])
def logout_bilibili():
    """B站登出"""
    try:
        result = run_async(login_service.logout())
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'登出失败: {str(e)}'
        }), 500


@app.route('/api/bilibili/login/check', methods=['GET'])
def check_current_login():
    """检查当前登录状态"""
    try:
        # 检查是否配置了核心登录凭据（BUVID3不是必需的）
        has_credentials = all([
            Config.BILIBILI_SESSDATA,
            Config.BILIBILI_BILI_JCT,
            Config.BILIBILI_DEDEUSERID
        ])

        if has_credentials:
            # 进一步验证凭据有效性
            bilibili_service = BilibiliService()
            is_valid = run_async(bilibili_service.check_credential_valid())

            return jsonify({
                'success': True,
                'data': {
                    'is_logged_in': is_valid,
                    'user_id': Config.BILIBILI_DEDEUSERID[:10] + '***' if Config.BILIBILI_DEDEUSERID else None,
                    'message': '已登录' if is_valid else '凭据已失效，请重新登录'
                }
            })
        else:
            return jsonify({
                'success': True,
                'data': {
                    'is_logged_in': False,
                    'user_id': None,
                    'message': '未登录'
                }
            })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'检查登录状态失败: {str(e)}'
        }), 500


if __name__ == '__main__':
    print(f"🚀 BiliBili视频总结系统启动中...")
    print(f"📡 服务地址: http://{Config.FLASK_HOST}:{Config.FLASK_PORT}")
    print(f"🤖 AI模型: {Config.OPENAI_MODEL}")
    print(f"=" * 50)
    
    app.run(
        host=Config.FLASK_HOST,
        port=Config.FLASK_PORT,
        debug=Config.FLASK_DEBUG
    )

